<script setup lang="ts">
import { storeToRefs } from "pinia";
import { useFuncStore } from "../../store";
import { nextTick, reactive, ref } from "vue";
import { ElMessage, ElMessageBox ,TreeInstance} from "element-plus";
import { ApiRole } from "../../api";

const { funcTree } = storeToRefs(useFuncStore());

const model = reactive<API.Role.Config>({
  role_id: 0,
  role_func_ids: "",
});
const defaultCheckedKeys = ref<number[]>([]);
const show = ref<boolean>(false);
// const formRef=ref<FormInstance|null>(null)
const emits = defineEmits<{ (name: "save", model: API.Role.Config): void }>();
const treeRef = ref<TreeInstance | null>(null);
const cancel = async () => {
  await ElMessageBox.confirm("取消数据会丢失哦？", "提示", { type: "warning" });
  show.value = false;
};
const save = async () => {
  
  // let checkedIds = [
    
  //   ...treeRef.value?.getCheckedKeys(),
  //   ...treeRef.value?.getHalfCheckedKeys(),
  // ]
  let checkedIds=[...(treeRef.value?.getCheckedKeys() ?? []),...(treeRef.value?.getHalfCheckedKeys() ?? [])]
  checkedIds.splice(checkedIds.indexOf(0), 1);
  model.role_func_ids = checkedIds.join(",");
  emits("save", model);
};
defineExpose({
  begin: async (role_id: number) => {
    model.role_id = role_id;
    // model.value.role_func_ids=data.role_func_ids
    const roleFuncs = await ApiRole.rolefunc(role_id);
    defaultCheckedKeys.value = roleFuncs.reduce(
      (result: Array<number>, func) => {
        if (func.func_key !== "") {
          result.push(func.func_id);
        }
        return result;
      },
      []
    );
    await nextTick(() => (show.value = true));
  },
  end: ()=>{
    show.value=false
  }
});
</script>

<template>
  <el-dialog title="功能分配" width="500px" v-model="show" destroy-on-close>
    <el-tree
    ref="treeRef"
      :data="funcTree"
      default-expand-all
      show-checkbox
      :expand-on-click-node="false"
      :props="{ label: 'func_name' }"
      node-key="func_id"
      :default-checked-keys="defaultCheckedKeys"
    >
    </el-tree>
    <div slot="footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<style scoped></style>
